package org.imagiccode.core.util;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.imagiccode.core.Constants;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import io.swagger.models.auth.In;

/**
 * web层的工具类
 *
 * @author 1340760685@qq.com
 * @create 2016-12-08 21:10
 **/
public final class WebUtil {
    private WebUtil() {
    }

    /**
     * 获取指定Cookie的值
     */
    public static final String getCookieValue(HttpServletRequest request, String cookieName, String defaultValue) {
        Cookie cookie = WebUtils.getCookie(request, cookieName);
        if (cookie == null) {
            return defaultValue;
        }
        return cookie.getValue();
    }

    /**
     * 保存当前用户
     */
    public static final void saveCurrentUser(Object user) {
        setSession(Constants.CURRENT_USER, user);
    }

    /**
     * 获取当前用户
     */
    public static final Integer getCurrentUser() {
        Subject currentUser = SecurityUtils.getSubject();
        if (null != currentUser) {
            Session session = currentUser.getSession();
            if (null != session) {
                return (Integer) session.getAttribute(Constants.CURRENT_USER);
            }
        }
        return null;
    }

    /**
     * 将一些数据放到ShiroSession中,以便于其它地方使用
     *
     * @see比如Controller,使用时直接用HttpSession.getAttribute(key)就可以取到
     */
    public static final void setSession(Object key, Object value) {
        Subject currentUser = SecurityUtils.getSubject();
        if (null != currentUser) {
            Session session = currentUser.getSession();
            if (null != session) {
                session.setAttribute(key, value);
            }
        }
    }
}
